<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能待办事项管理</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <script src="https://cdn.sheetjs.com/xlsx-0.19.3/package/dist/xlsx.full.min.js"></script>
    <style>
        :root {
            --primary-color: #4361ee;
            --secondary-color: #3f37c9;
            --success-color: #4cc9f0;
            --danger-color: #f72585;
            --warning-color: #f8961e;
            --info-color: #4895ef;
            --light-color: #f8f9fa;
            --dark-color: #212529;
        }

        body {
            background-color: #f8f9fa;
            padding-top: 20px;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        .app-container {
            max-width: 800px;
            margin: 0 auto;
        }

        .header-card {
            border: none;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            border-radius: 12px;
            overflow: hidden;
            margin-bottom: 20px;
        }

        .header-title {
            font-weight: 700;
            letter-spacing: 0.5px;
        }

        .task-card {
            margin-bottom: 12px;
            border-radius: 10px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
            transition: all 0.3s ease;
            border: none;
            overflow: hidden;
        }

        .task-card:hover {
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.1);
            transform: translateY(-2px);
        }

        .task-card.high-priority {
            border-left: 4px solid var(--danger-color);
        }

        .task-card.medium-priority {
            border-left: 4px solid var(--warning-color);
        }

        .task-card.low-priority {
            border-left: 4px solid var(--success-color);
        }

        .completed {
            opacity: 0.7;
            background-color: #f8f9fa;
        }

        .completed .task-text {
            text-decoration: line-through;
            color: #6c757d !important;
        }

        .subtask {
            margin-left: 40px;
            margin-top: 8px;
            border-left: 3px solid #e9ecef;
            padding-left: 15px;
            transition: all 0.3s ease;
        }

        .subtask-item {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 10px 15px;
            margin-bottom: 8px;
            transition: all 0.2s ease;
        }

        .subtask-item:hover {
            background-color: #e9ecef;
        }

        .has-subtasks::after {
            content: "›";
            margin-left: 8px;
            font-weight: bold;
            color: var(--primary-color);
            transition: transform 0.2s ease;
        }

        .has-subtasks.expanded::after {
            transform: rotate(90deg);
        }

        .due-date {
            font-size: 0.85rem;
            color: #6c757d;
            margin-left: 10px;
            display: inline-flex;
            align-items: center;
        }

        .due-date i {
            margin-right: 4px;
        }

        .overdue {
            color: var(--danger-color) !important;
            font-weight: bold;
        }

        .due-soon {
            color: var(--warning-color) !important;
        }

        .btn-export {
            background-color: var(--success-color);
            color: white;
        }

        .btn-import {
            background-color: var(--info-color);
            color: white;
        }

        .task-actions {
            opacity: 1;
        }

        .priority-badge {
            font-size: 0.75rem;
            padding: 3px 8px;
            border-radius: 10px;
            margin-left: 8px;
            font-weight: 600;
        }

        .priority-high {
            background-color: rgba(247, 37, 133, 0.1);
            color: var(--danger-color);
        }

        .priority-medium {
            background-color: rgba(248, 150, 30, 0.1);
            color: var(--warning-color);
        }

        .priority-low {
            background-color: rgba(76, 201, 240, 0.1);
            color: var(--success-color);
        }

        .search-box {
            position: relative;
        }

        .search-box i {
            position: absolute;
            left: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #6c757d;
        }

        .search-input {
            padding-left: 35px;
        }

        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #6c757d;
        }

        .empty-state i {
            font-size: 3rem;
            color: #dee2e6;
            margin-bottom: 15px;
        }

        .stats-card {
            background-color: white;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
            cursor: pointer;
            /* Add cursor pointer for clickable stats cards */
        }

        .stats-value {
            font-size: 1.5rem;
            font-weight: 700;
        }

        .stats-label {
            font-size: 0.85rem;
            color: #6c757d;
        }

        @media (max-width: 576px) {
            .task-actions {
                opacity: 1 !important;
            }

            .subtask {
                margin-left: 20px;
            }
        }
    </style>
</head>

<body>
    <div class="container app-container">
        <div class="card header-card">
            <div class="card-header bg-primary text-white">
                <div class="d-flex justify-content-between align-items-center">
                    <h3 class="mb-0 header-title"><i class="bi bi-check2-circle me-2"></i>智能待办事项</h3>
                    <div>
                        <button id="importBtn" class="btn btn-sm btn-import me-2">
                            <i class="bi bi-upload"></i> 导入
                        </button>
                        <button id="exportBtn" class="btn btn-sm btn-export">
                            <i class="bi bi-download"></i> 导出
                        </button>
                        <input type="file" id="fileInput" style="display: none;" accept=".xlsx,.xls">
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="row mb-3">
                    <div class="col-md-6 mb-2 mb-md-0">
                        <div class="search-box">
                            <i class="bi bi-search"></i>
                            <input type="text" id="searchInput" class="form-control search-input" placeholder="搜索任务...">
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="d-flex">
                            <input type="text" id="newTaskInput" class="form-control me-2" placeholder="添加新任务...">
                            <button id="addTaskBtn" class="btn btn-primary flex-shrink-0">添加</button>
                        </div>
                    </div>
                </div>

                <div class="d-flex align-items-center mb-3">
                    <div class="me-3">
                        <label for="taskDueDate" class="form-label mb-0">截止日期:</label>
                    </div>
                    <div class="me-3">
                        <input type="date" id="taskDueDate" class="form-control">
                    </div>
                    <div>
                        <select id="taskPriority" class="form-select">
                            <option value="">优先级</option>
                            <option value="high">高优先级</option>
                            <option value="medium">中优先级</option>
                            <option value="low">低优先级</option>
                        </select>
                    </div>
                </div>

                <div class="row mb-3">
                    <div class="col-md-3">
                        <div class="stats-card" id="uncompletedTasksCard">
                            <div class="stats-value text-warning" id="uncompletedTasks">0</div>
                            <div class="stats-label">未完成</div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stats-card" id="overdueTasksCard">
                            <div class="stats-value text-danger" id="overdueTasks">0</div>
                            <div class="stats-label">已过期</div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stats-card" id="completedTasksCard">
                            <div class="stats-value text-success" id="completedTasks">0</div>
                            <div class="stats-label">已完成</div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stats-card" id="totalTasksCard">
                            <div class="stats-value text-primary" id="totalTasks">0</div>
                            <div class="stats-label">总任务数</div>
                        </div>
                    </div>
                </div>

                <div id="taskList">
                    <!-- 任务列表将在这里动态生成 -->
                </div>
            </div>
        </div>
    </div>

    <!-- 子任务模态框 -->
    <div class="modal fade" id="subtaskModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加子任务</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="newSubtaskInput" class="form-label">子任务内容</label>
                        <input type="text" id="newSubtaskInput" class="form-control" placeholder="输入子任务内容...">
                    </div>
                    <div class="mb-3">
                        <label for="subtaskDueDate" class="form-label">截止日期</label>
                        <input type="date" id="subtaskDueDate" class="form-control">
                    </div>
                    <input type="hidden" id="currentTaskId">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" id="addSubtaskBtn" class="btn btn-primary">添加子任务</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <noscript>
        <style>
            body {
                display: none !important;
            }
        </style>
        <meta http-equiv="refresh" content="0; url=about:blank">
    </noscript>
    <script src="security.js"></script>
    <script>
        // 初始化应用
        document.addEventListener('DOMContentLoaded', function () {
            // 加载保存的任务
            loadTasks();

            // 添加任务事件
            document.getElementById('addTaskBtn').addEventListener('click', addTask);
            document.getElementById('newTaskInput').addEventListener('keypress', function (e) {
                if (e.key === 'Enter') addTask();
            });

            // 添加子任务事件
            document.getElementById('addSubtaskBtn').addEventListener('click', addSubtask);

            // 导入导出事件
            document.getElementById('exportBtn').addEventListener('click', exportToExcel);
            document.getElementById('importBtn').addEventListener('click', function () {
                document.getElementById('fileInput').click();
            });
            document.getElementById('fileInput').addEventListener('change', importFromExcel);

            // 搜索功能
            document.getElementById('searchInput').addEventListener('input', function () {
                renderTasks(); // Re-render tasks on search input
            });

            // 统计面板点击事件
            document.getElementById('uncompletedTasksCard').addEventListener('click', () => renderTasks('uncompleted'));
            document.getElementById('overdueTasksCard').addEventListener('click', () => renderTasks('overdue'));
            document.getElementById('completedTasksCard').addEventListener('click', () => renderTasks('completed'));
            document.getElementById('totalTasksCard').addEventListener('click', () => renderTasks('all'));

        });

        // 任务数据
        let tasks = [];
        let currentFilter = 'uncompleted'; // Default filter to uncompleted

        // 添加新任务
        function addTask() {
            const input = document.getElementById('newTaskInput');
            const dueDateInput = document.getElementById('taskDueDate');
            const prioritySelect = document.getElementById('taskPriority');

            if (input.value.trim() === '') return;

            const newTask = {
                id: Date.now(),
                text: input.value.trim(),
                completed: false,
                dueDate: dueDateInput.value || null,
                priority: prioritySelect.value || 'medium',
                subtasks: [],
                expanded: true,
                createdAt: new Date().toISOString()
            };

            tasks.unshift(newTask); // 添加到开头
            saveTasks();
            renderTasks();

            // 清空输入
            input.value = '';
            dueDateInput.value = '';
            prioritySelect.value = '';
            input.focus();
        }

        // 添加子任务
        function addSubtask() {
            const input = document.getElementById('newSubtaskInput');
            const dueDateInput = document.getElementById('subtaskDueDate');
            const taskId = parseInt(document.getElementById('currentTaskId').value);

            if (input.value.trim() === '') return;

            const task = tasks.find(t => t.id === taskId);
            if (task) {
                task.subtasks.push({
                    id: Date.now(),
                    text: input.value.trim(),
                    completed: false,
                    dueDate: dueDateInput.value || null,
                    createdAt: new Date().toISOString()
                });

                saveTasks();
                renderTasks();

                // 清空输入
                input.value = '';
                dueDateInput.value = '';

                // 关闭模态框
                bootstrap.Modal.getInstance(document.getElementById('subtaskModal')).hide();
            }
        }

        // 切换任务完成状态
        function toggleTaskCompletion(taskId) {
            const task = tasks.find(t => t.id === taskId);
            if (task) {
                task.completed = !task.completed;

                // 如果完成任务，自动完成所有子任务
                if (task.completed) {
                    task.subtasks.forEach(subtask => {
                        subtask.completed = true;
                    });
                    showCelebration();
                } else {
                    // 如果取消完成任务，自动取消所有子任务
                    task.subtasks.forEach(subtask => {
                        subtask.completed = false;
                    });
                }

                saveTasks();
                renderTasks();
            }
        }

        // 显示庆祝提示
        function showCelebration() {
            const celebration = document.createElement('div');
            celebration.innerHTML = `
                <div style="position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); 
                    background: rgba(0,0,0,0.7); color: white; padding: 20px 40px; 
                    border-radius: 10px; font-size: 24px; z-index: 1000;">
                    🎉 任务完成！ 🎉
                </div>
            `;
            document.body.appendChild(celebration);

            setTimeout(() => {
                celebration.remove();
            }, 700);
        }

        // 切换子任务完成状态
        function toggleSubtaskCompletion(taskId, subtaskId) {
            const task = tasks.find(t => t.id === taskId);
            if (task) {
                const subtask = task.subtasks.find(st => st.id === subtaskId);
                if (subtask) {
                    subtask.completed = !subtask.completed;
                    // 更新父任务状态
                    task.completed = task.subtasks.length > 0 && task.subtasks.every(st => st.completed);
                    saveTasks();
                    renderTasks();

                    // 显示庆祝提示
                    if (subtask.completed) {
                        showCelebration();
                    }
                }
            }
        }

        // 删除任务
        function deleteTask(taskId) {
            tasks = tasks.filter(t => t.id !== taskId);
            saveTasks();
            renderTasks();
        }

        // 删除子任务
        function deleteSubtask(taskId, subtaskId) {
            const task = tasks.find(t => t.id === taskId);
            if (task) {
                task.subtasks = task.subtasks.filter(st => st.id !== subtaskId);
                saveTasks();
                renderTasks();
            }
        }

        // 显示添加子任务模态框
        function showAddSubtaskModal(taskId) {
            document.getElementById('currentTaskId').value = taskId;
            document.getElementById('newSubtaskInput').value = '';
            document.getElementById('subtaskDueDate').value = '';

            const modal = new bootstrap.Modal(document.getElementById('subtaskModal'));
            modal.show();
            document.getElementById('newSubtaskInput').focus();
        }

        // 切换子任务列表的展开/折叠状态
        function toggleSubtasks(taskId) {
            const task = tasks.find(t => t.id === taskId);
            if (task) {
                task.expanded = !task.expanded;
                saveTasks();
                renderTasks();
            }
        }

        // 渲染任务列表
        function renderTasks(filter = currentFilter) {
            currentFilter = filter; // Update current filter
            const taskList = document.getElementById('taskList');
            const searchTerm = document.getElementById('searchInput').value.toLowerCase();
            const today = new Date();
            today.setHours(0, 0, 0, 0);

            // 过滤任务
            let filteredTasks = tasks.filter(task => {
                // 搜索匹配
                const matchesSearch = task.text.toLowerCase().includes(searchTerm) ||
                    (task.subtasks && task.subtasks.some(st => st.text.toLowerCase().includes(searchTerm)));

                if (!matchesSearch) return false;

                // 状态过滤
                if (filter === 'completed') {
                    return task.completed;
                } else if (filter === 'overdue') {
                    return !task.completed && task.dueDate && new Date(task.dueDate) < today;
                } else if (filter === 'all') {
                    return true; // Show all tasks (respecting search term)
                } else if (filter === 'uncompleted') {
                    return !task.completed;
                }
                return !task.completed; // Default to uncompleted tasks
            });

            taskList.innerHTML = '';

            if (filteredTasks.length === 0) {
                let emptyMessage = '点击"添加"按钮创建新任务';
                if (searchTerm) {
                    emptyMessage = '尝试不同的搜索词';
                } else if (filter === 'completed') {
                    emptyMessage = '没有已完成的任务';
                } else if (filter === 'overdue') {
                    emptyMessage = '没有已过期的任务';
                } else if (filter === 'uncompleted') {
                    emptyMessage = '没有未完成的任务';
                } else if (filter === 'all' && tasks.length > 0) {
                    emptyMessage = '没有匹配当前筛选条件的任务';
                } else if (tasks.length === 0) {
                    emptyMessage = '点击"添加"按钮创建新任务';
                }


                taskList.innerHTML = `
                    <div class="empty-state">
                        <i class="bi bi-check2-square"></i>
                        <h5>没有找到任务</h5>
                        <p class="text-muted">${emptyMessage}</p>
                    </div>
                `;
                updateStats();
                return;
            }

            filteredTasks.forEach(task => {
                const taskElement = document.createElement('div');
                let priorityClass = '';

                // 根据优先级添加类
                switch (task.priority) {
                    case 'high':
                        priorityClass = 'high-priority';
                        break;
                    case 'medium':
                        priorityClass = 'medium-priority';
                        break;
                    case 'low':
                        priorityClass = 'low-priority';
                        break;
                }

                taskElement.className = `task-card card ${priorityClass} ${task.completed ? 'completed' : ''}`;

                // 任务头部
                const taskHeader = document.createElement('div');
                taskHeader.className = 'card-body d-flex justify-content-between align-items-center';

                // 左侧内容
                const leftContent = document.createElement('div');
                leftContent.className = 'd-flex align-items-center flex-grow-1 pe-2';
                leftContent.style.minWidth = 0; // 防止文本溢出

                // 完成复选框
                const checkbox = document.createElement('input');
                checkbox.type = 'checkbox';
                checkbox.className = 'form-check-input me-2 flex-shrink-0';
                checkbox.checked = task.completed;
                checkbox.addEventListener('change', () => toggleTaskCompletion(task.id));
                leftContent.appendChild(checkbox);

                // 任务文本容器
                const textContainer = document.createElement('div');
                textContainer.className = 'flex-grow-1 text-truncate';

                // 任务文本
                const taskText = document.createElement('span');
                taskText.className = 'task-text fw-medium';
                taskText.textContent = task.text;
                textContainer.appendChild(taskText);

                // 子任务标记
                if (task.subtasks && task.subtasks.length > 0) {
                    taskText.classList.add('has-subtasks');
                    if (task.expanded) {
                        taskText.classList.add('expanded');
                    }
                }

                // 优先级标记
                if (task.priority) {
                    const priorityBadge = document.createElement('span');
                    priorityBadge.className = `priority-badge priority-${task.priority}`;

                    switch (task.priority) {
                        case 'high':
                            priorityBadge.textContent = '高优先级';
                            break;
                        case 'medium':
                            priorityBadge.textContent = '中优先级';
                            break;
                        case 'low':
                            priorityBadge.textContent = '低优先级';
                            break;
                    }

                    textContainer.appendChild(priorityBadge);
                }

                leftContent.appendChild(textContainer);

                // 截止日期
                if (task.dueDate) {
                    const dueDate = new Date(task.dueDate);

                    const dueDateElement = document.createElement('span');
                    dueDateElement.className = 'due-date flex-shrink-0';

                    // 检查是否过期或即将到期
                    if (dueDate < today && !task.completed) {
                        dueDateElement.classList.add('overdue');
                        dueDateElement.innerHTML = `<i class="bi bi-exclamation-triangle-fill"></i>${formatDate(dueDate)}`;
                    } else if ((dueDate - today) / (1000 * 60 * 60 * 24) <= 3 && !task.completed) {
                        dueDateElement.classList.add('due-soon');
                        dueDateElement.innerHTML = `<i class="bi bi-clock"></i>${formatDate(dueDate)}`;
                    } else {
                        dueDateElement.innerHTML = `<i class="bi bi-calendar"></i>${formatDate(dueDate)}`;
                    }

                    leftContent.appendChild(dueDateElement);
                }

                taskHeader.appendChild(leftContent);

                // 右侧操作按钮
                const rightContent = document.createElement('div');
                rightContent.className = 'task-actions d-flex flex-shrink-0';

                // 添加子任务按钮
                const addSubtaskBtn = document.createElement('button');
                addSubtaskBtn.className = 'btn btn-sm btn-outline-secondary me-2';
                addSubtaskBtn.innerHTML = '<i class="bi bi-list-nested"></i>';
                addSubtaskBtn.title = '添加子任务';
                addSubtaskBtn.addEventListener('click', (e) => {
                    e.stopPropagation();
                    showAddSubtaskModal(task.id);
                });
                rightContent.appendChild(addSubtaskBtn);

                // 删除按钮
                const deleteBtn = document.createElement('button');
                deleteBtn.className = 'btn btn-sm btn-outline-danger';
                deleteBtn.innerHTML = '<i class="bi bi-trash"></i>';
                deleteBtn.title = '删除任务';
                deleteBtn.addEventListener('click', (e) => {
                    e.stopPropagation();
                    if (confirm('确定要删除此任务及其所有子任务吗？')) {
                        deleteTask(task.id);
                    }
                });
                rightContent.appendChild(deleteBtn);

                taskHeader.appendChild(rightContent);

                // 点击任务头部切换子任务展开状态
                taskHeader.style.cursor = 'pointer';
                taskHeader.addEventListener('click', (e) => {
                    // 只有当点击的是任务文本区域时才切换展开状态
                    if (e.target.closest('.task-text') ||
                        (e.target === textContainer && !e.target.closest('input'))) {
                        toggleSubtasks(task.id);
                    }
                });

                taskElement.appendChild(taskHeader);

                // 子任务列表
                if (task.subtasks && task.subtasks.length > 0 && task.expanded) {
                    const subtaskList = document.createElement('div');
                    subtaskList.className = 'subtask-list p-2';

                    // 过滤子任务（如果正在搜索）
                    let subtasksToShow = task.subtasks;
                    if (searchTerm) {
                        subtasksToShow = task.subtasks.filter(st =>
                            st.text.toLowerCase().includes(searchTerm))
                    }

                    if (subtasksToShow.length > 0) {
                        subtasksToShow.forEach(subtask => {
                            const subtaskElement = document.createElement('div');
                            subtaskElement.className = `subtask ${subtask.completed ? 'completed' : ''}`;

                            const subtaskItem = document.createElement('div');
                            subtaskItem.className = 'subtask-item d-flex justify-content-between align-items-center';

                            // 左侧内容
                            const subtaskLeft = document.createElement('div');
                            subtaskLeft.className = 'd-flex align-items-center flex-grow-1 pe-2';
                            subtaskLeft.style.minWidth = 0;

                            // 子任务复选框
                            const subtaskCheckbox = document.createElement('input');
                            subtaskCheckbox.type = 'checkbox';
                            subtaskCheckbox.className = 'form-check-input me-2 flex-shrink-0';
                            subtaskCheckbox.checked = subtask.completed;
                            subtaskCheckbox.addEventListener('change', () => toggleSubtaskCompletion(task.id, subtask.id));
                            subtaskLeft.appendChild(subtaskCheckbox);

                            // 子任务文本
                            const subtaskText = document.createElement('span');
                            subtaskText.className = 'subtask-text text-truncate';
                            subtaskText.textContent = subtask.text;
                            subtaskLeft.appendChild(subtaskText);

                            // 子任务截止日期
                            if (subtask.dueDate) {
                                const dueDate = new Date(subtask.dueDate);

                                const dueDateElement = document.createElement('span');
                                dueDateElement.className = 'due-date flex-shrink-0';

                                // 检查是否过期或即将到期
                                if (dueDate < today && !subtask.completed) {
                                    dueDateElement.classList.add('overdue');
                                    dueDateElement.innerHTML = `<i class="bi bi-exclamation-triangle-fill"></i>${formatDate(dueDate)}`;
                                } else if ((dueDate - today) / (1000 * 60 * 60 * 24) <= 3 && !subtask.completed) {
                                    dueDateElement.classList.add('due-soon');
                                    dueDateElement.innerHTML = `<i class="bi bi-clock"></i>${formatDate(dueDate)}`;
                                } else {
                                    dueDateElement.innerHTML = `<i class="bi bi-calendar"></i>${formatDate(dueDate)}`;
                                }

                                subtaskLeft.appendChild(dueDateElement);
                            }

                            subtaskItem.appendChild(subtaskLeft);

                            // 右侧删除按钮
                            const subtaskDeleteBtn = document.createElement('button');
                            subtaskDeleteBtn.className = 'btn btn-sm btn-outline-danger flex-shrink-0';
                            subtaskDeleteBtn.innerHTML = '<i class="bi bi-trash"></i>';
                            subtaskDeleteBtn.title = '删除子任务';
                            subtaskDeleteBtn.addEventListener('click', (e) => {
                                e.stopPropagation();
                                if (confirm('确定要删除此子任务吗？')) {
                                    deleteSubtask(task.id, subtask.id);
                                }
                            });
                            subtaskItem.appendChild(subtaskDeleteBtn);

                            subtaskElement.appendChild(subtaskItem);
                            subtaskList.appendChild(subtaskElement);
                        });

                        taskElement.appendChild(subtaskList);
                    }
                }

                taskList.appendChild(taskElement);
            });

            updateStats();
        }

        // 更新统计信息
        function updateStats() {
            const totalTasks = tasks.length;
            const completedTasksCount = tasks.filter(t => t.completed).length;
            const uncompletedTasksCount = totalTasks - completedTasksCount;

            let overdueTasksCount = 0;
            const today = new Date();
            today.setHours(0, 0, 0, 0);

            tasks.forEach(task => {
                // 检查主任务
                if (task.dueDate && !task.completed) {
                    const dueDate = new Date(task.dueDate);
                    if (dueDate < today) overdueTasksCount++;
                }

                // 检查子任务 (子任务过期不单独计入，父任务过期即可)
            });

            document.getElementById('totalTasks').textContent = totalTasks;
            document.getElementById('completedTasks').textContent = completedTasksCount;
            document.getElementById('overdueTasks').textContent = overdueTasksCount;
            document.getElementById('uncompletedTasks').textContent = uncompletedTasksCount;
        }

        // 格式化日期显示
        function formatDate(date) {
            const today = new Date();
            today.setHours(0, 0, 0, 0);

            const tomorrow = new Date(today);
            tomorrow.setDate(tomorrow.getDate() + 1);

            if (date.toDateString() === today.toDateString()) {
                return '今天';
            } else if (date.toDateString() === tomorrow.toDateString()) {
                return '明天';
            } else {
                return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
            }
        }

        // 保存任务到本地存储
        function saveTasks() {
            localStorage.setItem('tasks', JSON.stringify(tasks));
        }

        // 从本地存储加载任务
        function loadTasks() {
            const savedTasks = localStorage.getItem('tasks');
            tasks = savedTasks ? JSON.parse(savedTasks) : [];

            // 确保每个任务都有必要的属性
            tasks.forEach(task => {
                if (!task.subtasks) task.subtasks = [];
                if (task.expanded === undefined) task.expanded = true;
                if (!task.priority) task.priority = 'medium';
            });

            renderTasks('uncompleted'); // Load with 'uncompleted' filter initially
        }

        // 导出到Excel
        function exportToExcel() {
            // 准备数据
            const data = [];

            // 添加表头
            data.push(['任务', '状态', '优先级', '截止日期', '创建时间', '子任务', '子任务状态', '子任务截止日期', '子任务创建时间']);

            // 添加任务数据
            tasks.forEach(task => {
                // 主任务行
                data.push([
                    task.text,
                    task.completed ? '已完成' : '未完成',
                    task.priority === 'high' ? '高' : task.priority === 'medium' ? '中' : '低',
                    task.dueDate ? formatDate(new Date(task.dueDate)) : '',
                    formatDateTime(new Date(task.createdAt)),
                    '', '', '', ''
                ]);

                // 子任务行
                task.subtasks.forEach(subtask => {
                    data.push([
                        '', '', '', '', '',
                        subtask.text,
                        subtask.completed ? '已完成' : '未完成',
                        subtask.dueDate ? formatDate(new Date(subtask.dueDate)) : '',
                        formatDateTime(new Date(subtask.createdAt))
                    ]);
                });
            });

            // 创建工作簿
            const wb = XLSX.utils.book_new();
            const ws = XLSX.utils.aoa_to_sheet(data);
            XLSX.utils.book_append_sheet(wb, ws, '待办事项');

            // 导出文件
            XLSX.writeFile(wb, `待办事项_${new Date().toISOString().slice(0, 10)}.xlsx`);
        }

        // 从Excel导入
        function importFromExcel(event) {
            const file = event.target.files[0];
            if (!file) return;

            const reader = new FileReader();
            reader.onload = function (e) {
                const data = new Uint8Array(e.target.result);
                const workbook = XLSX.read(data, { type: 'array' });

                // 获取第一个工作表
                const worksheet = workbook.Sheets[workbook.SheetNames[0]];
                const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

                // 解析数据
                const newTasks = [];
                let currentTask = null;

                // 跳过表头
                for (let i = 1; i < jsonData.length; i++) {
                    const row = jsonData[i];

                    // 主任务行
                    if (row[0]) {
                        if (currentTask) {
                            newTasks.push(currentTask);
                        }

                        currentTask = {
                            id: Date.now() + i,
                            text: row[0],
                            completed: row[1] === '已完成',
                            priority: row[2] === '高' ? 'high' : row[2] === '中' ? 'medium' : 'low',
                            dueDate: row[3] ? parseExcelDate(row[3]) : null,
                            subtasks: [],
                            expanded: true,
                            createdAt: row[4] ? (parseExcelDate(row[4]) ? new Date(parseExcelDate(row[4])).toISOString() : new Date().toISOString()) : new Date().toISOString()
                        };
                    }

                    // 子任务行
                    if (currentTask && row[5]) {
                        const subtaskDueDate = row[7] ? parseExcelDate(row[7]) : null;
                        const subtaskCreatedAt = row[8] ? (parseExcelDate(row[8]) ? new Date(parseExcelDate(row[8])).toISOString() : new Date().toISOString()) : new Date().toISOString();
                        currentTask.subtasks.push({
                            id: Date.now() + i + 10000, // 确保ID不同
                            text: row[5],
                            completed: row[6] === '已完成',
                            dueDate: subtaskDueDate,
                            createdAt: subtaskCreatedAt
                        });
                    }
                }

                // 添加最后一个任务
                if (currentTask) {
                    newTasks.push(currentTask);
                }

                // 确认导入
                if (newTasks.length > 0 && confirm(`确定要导入 ${newTasks.length} 个任务吗？这将覆盖当前所有任务。`)) {
                    tasks = newTasks;
                    saveTasks();
                    renderTasks();
                }

                // 清空文件输入
                event.target.value = '';
            };

            reader.readAsArrayBuffer(file);
        }

        // 解析Excel中的日期
        function parseExcelDate(dateStr) {
            // 尝试解析中文日期格式
            const cnDateRegex = /(\d{4})年(\d{1,2})月(\d{1,2})日/;
            const match = dateStr.match(cnDateRegex);

            if (match) {
                const year = parseInt(match[1]);
                const month = parseInt(match[2]) - 1;
                const day = parseInt(match[3]);
                return new Date(year, month, day).toISOString().split('T')[0];
            }

            // 尝试解析"今天"、"明天"
            if (dateStr === '今天') {
                return new Date().toISOString().split('T')[0];
            } else if (dateStr === '明天') {
                const tomorrow = new Date();
                tomorrow.setDate(tomorrow.getDate() + 1);
                return tomorrow.toISOString().split('T')[0];
            }

            // 默认返回 null
            return null;
        }

        // 格式化日期时间
        function formatDateTime(date) {
            return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日 ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
        }
    </script>
</body>

</html>